#include "userlib.h"

void printwritablevma(void)
{
	list<struct Range>::iterator it;
	if(writablevma.size()){
		printf("%7s%17s%17s%17s\n", "pid", "start", "end", "len");
		for( it = writablevma.begin(); it != writablevma.end(); ++it )
			printf("%7ld%17lx%17lx%17lx\n", (long)(*it).pid, (*it).start, (*it).end, (long)((*it).end-(*it).start));
	}
}

int haswritablevma(void)
{
	FILE *fp;
	char filename[30];
	char line[200];
	int i;
	vector<long> tasks;
	unsigned long start, end;
	char priv[5], str[20];
	
	gettracedtasks(&tasks);
	for(i = 0; i < tasks.size(); i++ ) {
		sprintf(filename, "/proc/%ld/maps", tasks[i]);
		fp = fopen(filename, "r");
		if(fp == NULL)
			die(filename);
		while(fgets(line, sizeof(line)-1, fp) != NULL){
			sscanf(line, "%lx-%lx %s %*s %s %*s %*s", &start, &end, priv, str);
			if(priv[1]=='w'){
				fclose(fp);
				return 1;
			}
		}
		fclose(fp);
	}
	return 0;
}

void getwritablevma(void)
{
	FILE *fp;
	char filename[30];
	char line[200];
	unsigned long start;
	unsigned long end;
	char priv[5];
	char str[20];
	unsigned i;
	vector<long> tasks;
	
	gettracedtasks(&tasks);
	writablevma.clear();
	for(i = 0; i < tasks.size(); i++ ) {
		sprintf(filename, "/proc/%ld/maps", tasks[i]);
		fp = fopen(filename, "r");
		if(fp == NULL)
			die(filename);
		while(fgets(line, sizeof(line)-1, fp) != NULL){
			sscanf(line, "%lx-%lx %s %*s %s %*s %*s", &start, &end,
					priv, str);
			if(priv[1]=='w'){
				Range r;
				r.pid=tasks[i];
				r.start=start;
				r.end=end;
				writablevma.push_back(r);
			}
		}
		fclose(fp);
	}
}

